require('./scss/main.scss')
let React = require('react')
let imageDatas = require( './imagesDatas.json')


//利用自执行函数,将图片名信息转成图片URL路径信息
imageDatas = (function genImageURL(imageDatasArr) {
    for (let i = 0, j = imageDatasArr.length; i < j; i++) {
        let singleImageData = imageDatasArr[i];

        singleImageData.imageURL = require(`./images/${singleImageData.fileName}`)

        imageDatasArr[i] = singleImageData
    }
    return imageDatasArr;
})(imageDatas)

function get30DegRandom(){
    return((Math.random() > 0.5 ? '' : '-') + Math.ceil(Math.random() * 30))
}
class ControllerUnit extends React.Component {

    handleClick = e => {
        const { arrange } = this.props;
        if (arrange && arrange.isCenter) {
            this.props.inverse();
        }else{
            this.props.center();
        }
        e.preventDefault();
        e.stopPropagation();
    }
    render() {
        const { arrange } = this.props
        let navigationClassName = "controller-unit ";
        navigationClassName += arrange && arrange.isCenter ? 'is-center ': '';
        navigationClassName += arrange && arrange.isInverse ? 'is-inverse ' : '';
        return(
            <span className={navigationClassName} onClick={this.handleClick}></span>
        )
    }
}
class ImgFigure extends React.Component{
    /**
     * imgFigure的点击处理函数
     * @returns {XML}
     */
    handleClick = event => {
        if (this.props.arrange && this.props.arrange.isCenter) {
            this.props.inverse()
        }else{
            this.props.center()
        }
        event.stopPropagation();
        event.preventDefault();
    }
    render(){
        let styleObj = {}
        const { arrange } = this.props
        if(arrange && arrange.pos){
            styleObj.left = arrange.pos.left
            styleObj.top = arrange.pos.top
        }
        let rotate =arrange && arrange.rotate

        //如果图片的旋转角度有值并且不为0，添加旋转角度
        if(rotate) {
            (['Moz', 'ms', 'webkit', '']).forEach(function (value){
                styleObj[`${value}transform`] = `rotate(${rotate}deg)`;
            });
        }

        let imgPaiClassName = "img-pai ";
        imgPaiClassName += arrange && arrange.isInverse ? 'is-inverse': '';
        return (
            <div className={imgPaiClassName} style={styleObj}>
                <div id="figure_img_Figure2333" className="img-figure" onClick={this.handleClick}>
                    <img className="img-picture" src={this.props.data.imageURL}
                         alt={this.props.data.title}
                    />
                    <div>
                        <h2 className="img-title">{this.props.data.title}</h2>
                    </div>
                </div>
                <div className="img-back" onClick={this.handleClick}>
                    <p>
                        {this.props.data.desc}
                    </p>
                </div>
            </div>
        )
    }
}

class ReactGallery extends React.Component{
    constructor(props) {
        super(props)
        this.state = {
            imgsArrangeArr: [
                {
                    pos: {
                        left: '0',
                        top: '0'
                    },
                    rotate: 0, //旋转角度
                    isInverse: false, //图片正反面
                    isCenter: false//图片是否居中
                }
            ]
        }
        this.Constant = {
            centerPos: {
                left: 0,
                right: 0
            },
            hPosRange: { //水平方向的取值范围
                leftSecX: [0, 0],
                rightSecX: [0, 0],
                y:[0, 0]
            },
            vPosRange: { //垂直方向的取值范围
                x: [0, 0],
                topY: [0, 0]
            }
        }
    }
    componentWillMount(){
        let imgsArrangeArr = []
        imageDatas.forEach(function(value, index){
            imgsArrangeArr[index] = {
                pos: {
                    left: 0,
                    top: 0
                },
                rotate: 0,
                isInverse: false,
                isCenter:false
            }
        })
        this.setState({imgsArrangeArr})
    }
    componentDidMount() {
        //首先拿到舞台的大小
        let stageDOM = this.stage,
            stageW = stageDOM.scrollWidth,
            stageH = stageDOM.scrollHeight,
            halfStageW = Math.ceil(stageW / 2),
            halfStageH = Math.ceil(stageH / 2);


        //拿到一个imageFigure的大小
        let imgFigureDOM = document.getElementById("figure_img_Figure2333"),
            imgW = imgFigureDOM.scrollWidth,
            imgH = imgFigureDOM.scrollHeight,
            halfImgW = Math.ceil(imgW / 2),
            halfImgH = Math.ceil(imgH / 2);

        //计算中心图片的位置点
        this.Constant.centerPos = {
            left: halfStageW - halfImgW,
            top: halfStageH - halfImgH
        }

        this.Constant.hPosRange.leftSecX[0] = -halfImgW;
        this.Constant.hPosRange.leftSecX[1] = halfStageW - halfImgW * 3;
        this.Constant.hPosRange.rightSecX[0] = halfStageW + halfImgW;
        this.Constant.hPosRange.rightSecX[1] = stageW - halfImgW;
        this.Constant.hPosRange.y[0] = -halfImgH;
        this.Constant.hPosRange.y[1] = stageH - halfImgH;

        this.Constant.vPosRange.topY[0] = -halfImgH;
        this.Constant.vPosRange.topY[1] = halfStageH - halfImgH * 3;
        this.Constant.vPosRange.x[0] = halfImgW - imgW;
        this.Constant.vPosRange.x[1] = halfImgW;

        this.rearrange(0);
    }

    getRangeRandom = (low, high) => {
        return Math.ceil(Math.random() * (high - low) + low);
    }

    inverse = (index) => {
        return function(){
            let imgsArrangeArr = this.state.imgsArrangeArr;
            imgsArrangeArr[index].isInverse = !imgsArrangeArr[index].isInverse;
            this.setState({
                imgsArrangeArr: imgsArrangeArr
            })
        }.bind(this);
    }
    center =  index => {
        return () =>{
            this.rearrange(index)
        }
    }
    rearrange = (centerIndex) =>  {
        let imgsArrangeArr = this.state.imgsArrangeArr,
            Constant = this.Constant,
            centerPos = Constant.centerPos,
            hPosRange = Constant.hPosRange,
            vPosRange = Constant.vPosRange,
            hPosRangeLeftSecX = hPosRange.leftSecX,
            hPosRangeRightSecX = hPosRange.rightSecX,
            hPosRangeY = hPosRange.y,
            vPosRangeTopY = vPosRange.topY,
            vPosRangeX = vPosRange.x,

            imgsArrangeTopArr = [],
            topImgNum = Math.ceil(Math.random() * 1),
            topImgSpliceIndex = 0,
            imgsArrangeCenterArr = imgsArrangeArr.splice(centerIndex, 1)

        //首先居中 centerIndex 的图片
        //居中的centerIndex的图片不需要旋转
        imgsArrangeCenterArr[0]={
            pos: centerPos,
            rotate: 0,
            isCenter: true
        };

        //取出要布局上侧的图片的状态信息
        topImgSpliceIndex = Math.ceil(Math.random() * (
            imgsArrangeArr.length - topImgNum));
        imgsArrangeTopArr = imgsArrangeArr.splice(topImgSpliceIndex, topImgNum);

        //布局位于上侧的图片
        imgsArrangeTopArr.forEach(function(value, index){
            imgsArrangeTopArr[index] = {
                pos: {
                    top: this.getRangeRandom(vPosRangeTopY[0], vPosRangeTopY[1]),
                    left: this.getRangeRandom(vPosRangeX[0], vPosRangeX[1])
                },
                rotate: get30DegRandom(),
                isCenter: false,
            };
        }.bind(this));

        //布局左右两侧的图片
        for (let i = 0, j = imgsArrangeArr.length, k = j / 2; i < j; i++) {
            let hPosRangeLORX = null;
            //前半部分布局左边, 右半部分布局右边
            if (i < k) {
                hPosRangeLORX = hPosRangeLeftSecX;
            }else {
                hPosRangeLORX = hPosRangeRightSecX;
            }
            imgsArrangeArr[i] = {
                pos: {
                    top: this.getRangeRandom(hPosRangeY[0], hPosRangeY[1]),
                    left: this.getRangeRandom(hPosRangeLORX[0], hPosRangeLORX[1])
                },
                rotate: get30DegRandom(),
                isCenter: false
            }
        }
        if(imgsArrangeTopArr && imgsArrangeTopArr[0]) {
            imgsArrangeArr.splice(topImgSpliceIndex, 0, imgsArrangeTopArr[0]);
        }

        imgsArrangeArr.splice(centerIndex, 0, imgsArrangeCenterArr[0]);

        this.setState({
            imgsArrangeArr:imgsArrangeArr
        });

    }
    render(){
        let controllerUnits = [],
            imgFigures = [];
        const { imgsArrangeArr } = this.state
        imageDatas.forEach(function(value, index){
            imgFigures.push(<ImgFigure key={index}
                                       data={value}
                                       arrange={imgsArrangeArr[index]}
                                       inverse={this.inverse(index)}
                                       center={this.center(index)}
            />);
            controllerUnits.push(<ControllerUnit key={index} arrange={imgsArrangeArr[index]} center={this.center(index)} inverse={this.inverse(index)}/>)
        }.bind(this))
        return(
            <section className="stage" ref={stage => this.stage = stage}>
                <section className="img-sec">
                    {imgFigures}
                </section>
                <nav className="controller-nav">
                    {controllerUnits}
                </nav>
            </section>
        )
    }
}

export default ReactGallery


